﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Components_PromotionProduct : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //string SaleOrderRequestID = Server.HtmlEncode(Utils.KillChars(Page.RouteData.Values["Param"].ToString()));
            //loadData(int.Parse(SaleOrderRequestID));

            string SaleOrderRequestID = "";
            if (Session["SaleOrderID"] != null)
            {
                SaleOrderRequestID = Session["SaleOrderID"].ToString();
                // Session["SaleOrderID"] = null;
                // Session.Remove("SaleOrderID");
                loadPromotion(int.Parse(SaleOrderRequestID));
            }
            else
            {
                Response.Redirect("~/san-pham", true);
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        UpdatePromotion(int.Parse(Session["SaleOrderID"].ToString()));
        Response.Redirect("~/dat-hang-thanh-cong/" + Session["SaleOrderID"].ToString(), true);
    }

    private void UpdatePromotion(int SaleOrderRequestID)
    {
        try
        {
            List<SaleOrderRequestPromotion> listPro = new List<SaleOrderRequestPromotion>();
            foreach (GridViewRow row in gvPromotion.Rows)
            {
                int ProductID = int.Parse(row.Cells[2].Text);
                int PromotionDetailID = int.Parse(row.Cells[4].Text);
                int PromotionID = int.Parse(row.Cells[3].Text);
                RadNumericTextBox QuantitySelect = (RadNumericTextBox)row.FindControl("txtQuantitySelect");
                int PromotionRemainQty = int.Parse(row.Cells[8].Text);

                SaleOrderRequestPromotion saleOrderPromotion = db.SaleOrderRequestPromotions.FirstOrDefault(a => a.SaleOrderRequestID == SaleOrderRequestID && a.ProductID == ProductID);
                saleOrderPromotion.QuantitySelect = int.Parse(QuantitySelect.Text);
                saleOrderPromotion.PromotionRemainQty = PromotionRemainQty;
                saleOrderPromotion.CreatedBy = "Web";
                saleOrderPromotion.LastUpdatedBy = "Web";
                saleOrderPromotion.CreatedDateTime = DateTime.Now;
                saleOrderPromotion.LastUpdatedDateTime = DateTime.Now;
                saleOrderPromotion.Status = 'N';//Moi luu
                listPro.Add(saleOrderPromotion);
            }
            db.Update<SaleOrderRequestPromotion>(listPro);
            db.SubmitChanges();
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("PromotionProduct-UpdatePromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void loadPromotion(int SaleOrderRequestID)
    {
        try
        {
            var lisrPromotion = (from p in db.SaleOrderRequestPromotions
                                 join a in db.Products on p.ProductID equals a.ID
                                 where p.SaleOrderRequestID == SaleOrderRequestID
                                 orderby p.QuantitySelect descending
                                 select new
                                 {
                                     Image = a.ImagePath,
                                     ProductName = a.ProductName,
                                     PromotionQuantity = p.PromotionRemainQty,
                                     PromotionQuantitySelect = p.QuantitySelect,
                                     PromotionID = p.PromotionID,
                                     PromotionDetailID = p.PromotionDetailID,
                                     ProductCode = a.ProductCode,
                                     Weight = p.Weight,
                                     p.ProductID
                                 }).ToList();

            // List<SaleOrderRequestPromotion> lisrPromotion = (List<SaleOrderRequestPromotion>)Session["listPromotion"];
            gvPromotion.DataSource = lisrPromotion;
            gvPromotion.DataBind();

            ViewState["dtPromotion"] = lisrPromotion.ToDataTable();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("PromotionProduct-loadPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    protected void txtQuantitySelectPro_TextChanged(object sender, EventArgs e)
    {
        try
        {
            RadNumericTextBox radNumeric = (RadNumericTextBox)sender;
            string QtySelect = radNumeric.Text == "" ? "0" : radNumeric.Text;

            GridViewRow currentItem = (GridViewRow)radNumeric.NamingContainer;

            string ProductID = currentItem.Cells[2].Text;

            string Weight = currentItem.Cells[5].Text;

            int TotalWeightSelect = Convert.ToInt32(QtySelect) * Convert.ToInt32(Weight);

            int totalWeight = int.Parse(db.SaleOrderRequests.FirstOrDefault(so => so.ID == int.Parse(Session["SaleOrderID"].ToString())).TotalWeight.ToString());

            if (ViewState["dtPromotion"] != null)
            {
                DataTable dtPro = (DataTable)ViewState["dtPromotion"];

                DataRow[] rowArr = dtPro.Select("ProductID='" + ProductID + "'");
                if (Convert.ToInt32(QtySelect) < 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được nhỏ hơn 0");
                    radNumeric.Text = "0";
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = "0";
                    return;
                }

                if (rowArr.Count() > 0)
                {
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = QtySelect;
                }

                int sumWeightSelected = Convert.ToInt32(dtPro.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"]) * IntOrNull(dr["PromotionQuantitySelect"])));
                int totalWeightRemain = totalWeight - sumWeightSelected;
                if (totalWeightRemain < 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được vượt quá số lượng khuyến mãi");
                    radNumeric.Text = "0";
                    DataRow row = rowArr[0];
                    row["PromotionQuantitySelect"] = "0";
                    return;
                }
                int PromotionQuantity = 0;
                foreach (DataRow r in dtPro.Rows)
                {
                    PromotionQuantity = totalWeightRemain / Convert.ToInt32(r["Weight"]);
                    r["PromotionQuantity"] = PromotionQuantity;
                }
                ViewState["dtPromotion"] = dtPro;
                bindingPromotion(dtPro);
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("PromotionProduct-txtQuantitySelectPro_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void bindingPromotion(DataTable dtPro)
    {
        if (dtPro.Rows.Count > 5)
        {
            gvPromotion.Height = 150;
            // gvPromotion.ClientSettings.Scrolling.AllowScroll = true;
        }
        //gvPromotion.ClientSettings.Scrolling.UseStaticHeaders = true;
        gvPromotion.DataSource = dtPro;
        gvPromotion.DataBind();

    }
    private decimal? DecimalOrNull(object val)
    {
        try
        {
            return Convert.ToDecimal(val);
        }
        catch
        {
            return null;
        }
    }

    private int? IntOrNull(object val)
    {
        try
        {
            return Convert.ToInt32(val);
        }
        catch
        {
            return null;
        }
    }
    protected void btnViewSO_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/dat-hang-thanh-cong", true);
    }
}